package com.boot.apollo.modules.thread;


import lombok.var;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/thread")
public class DeferredResultTest {


    @GetMapping("/deferred/{type}")
    public DeferredResult<ResponseEntity<List<String>>> pollNotification(@PathVariable int type) {

        DeferredResultWrapper deferredResultWrapper = new DeferredResultWrapper();

        if(type == 1) {
            deferredResultWrapper
                    .onTimeout(() -> {
                        System.out.println(deferredResultWrapper);
                        System.out.println("timeout");
                    });



            deferredResultWrapper.onCompletion(() -> {
                System.out.println(deferredResultWrapper);
                System.out.println("onCompletion");

            });

            CompletableFuture.supplyAsync(this::execute)
                    .whenCompleteAsync((result, throwable) -> deferredResultWrapper.setResult(result));

        } else {
            deferredResultWrapper.setResult("hello");
        }

        return deferredResultWrapper.getResult();

    }


    public String execute() {
        try {
            Thread.sleep(5000);
            System.out.println("Slow task executed");

            return "Task finished";
        } catch (InterruptedException e) {
            throw new RuntimeException();
        }
    }



}
